package com.example.dangerouscargodriver.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.baiju.netmanager.Http.IHttpRequest;
import com.baiju.style.citylist.Toast.ToastUtils;
import com.example.dangerouscargodriver.controller.AuthController;
import com.example.dangerouscargodriver.controller.EnterPlatformInfoController;
import com.example.dangerouscargodriver.controller.UserInfoController;
import com.example.dangerouscargodriver.entry.LogInInfo;
import com.example.dangerouscargodriver.param.RemoteAPI;
import com.example.dangerouscargodriver.param.RemoteAPICmd;
import com.example.dangerouscargodriver.module.ResponseInfo;
import com.example.dangerouscargodriver.utils.TextUtils;
import com.example.dangerouscargodriver.widget.ActionBar;
import com.example.dangerouscargodriver.R;
import com.example.dangerouscargodriver.ui.fragment.mine.MineFragment;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LogInActivity extends HttpRequestActivity implements View.OnClickListener{

    private static final String TAG = "LogInActivity";
    private ActionBar mActionBar = null;
    private TextView mProtocol = null;
    private EditText mTelephone = null;
    private EditText mCode = null;
    private Button mVCodeButton = null;
    private Button mLoginButton = null;

    private MyHandler mHandler = null;
    private static final int MSG_SHOW_TOAST = 1;
    private static final int MSG_TIMEOUT_COUNT = 2;
    private static final int MSG_EXIT_ACTIVITY = 3;

    private boolean mIsTimeout = false;

    private class MyHandler extends Handler {
        WeakReference<LogInActivity> mActivity;

        MyHandler(LogInActivity activity) {
            mActivity = new WeakReference<LogInActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            LogInActivity activity = mActivity.get();
            switch (msg.what){
                case MSG_TIMEOUT_COUNT:
                    int count = (int)msg.obj;
                    if(count > 0){
                        Message count_msg = new Message();
                        count_msg.what = MSG_TIMEOUT_COUNT;
                        count_msg.obj = count - 1;
                        activity.mVCodeButton.setText(Integer.toString(count) + "秒");
                        activity.mHandler.sendMessageDelayed(count_msg, 1000);
                    }
                    else{
                        activity.mIsTimeout = true;
                        activity.mVCodeButton.setText(R.string.btn_get_verify_code);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.initHttpComponent(LogInActivity.class);
        setContentView(R.layout.activity_log_in);

        mProtocol = findViewById(R.id.tv_protocol);

        TextUtils.getBuilder().click(getResources().getString(R.string.company_partner_protocol_login), getResources().getColor(R.color.red), new TextUtils.OnClickListener() {
            @Override
            public void onClick(int position) {
                switch (position){
                    case 0:
                        //跳转链接
                        Intent intent = new Intent(LogInActivity.this, ShowHtmlActivity.class);
                        intent.putExtra("type", "3");
                        startActivity(intent);
                        break;
                    case 1:
                        Intent intent2 = new Intent(LogInActivity.this, ShowHtmlActivity.class);
                        intent2.putExtra("type", "2");
                        startActivity(intent2);
                        break;
                }
            }
        }, "《危司机用户服务协议》", "《危司机隐私政策》").clickInto(mProtocol);
        mProtocol.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);

        mTelephone = findViewById(R.id.ed_login_telephone);
        mLoginButton = findViewById(R.id.btn_login);
        mLoginButton.setOnClickListener(this);

        mVCodeButton = findViewById(R.id.btn_send_verify_code);
        mVCodeButton.setOnClickListener(this);

        mCode = findViewById(R.id.ed_login_verify_code);

        mActionBar = findViewById(R.id.actionBarLogin);
        mActionBar.setOnBackClickListener( new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("isLogIn", 0);
                setResult(MineFragment.ACTION_LOGIN, intent);
                finish();
            }
        });

        mHandler = new MyHandler(this);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btn_login){
            if(!mTelephone.getText().toString().equals("")) {
                if(mCode.getText().toString().equals("")){
                    ToastUtils.showLongToast(LogInActivity.this, "请输入校验码！");
                }
                if(mIsTimeout){
                    ToastUtils.showLongToast(LogInActivity.this, "校验码已超时，请重新获取校验码！");
                }
                else{
                    showLoadingDialog();
                    HashMap<String, String> param = new HashMap<String, String>();
                    param.put("phone", mTelephone.getText().toString());
                    param.put("vcode", mCode.getText().toString());

                    sendHttpRequest(IHttpRequest.RequestMethod.POST_METHOD,
                            RemoteAPI.REQUEST_LOGIN,
                            null,
                            param,
                            RemoteAPICmd.REQUEST_LOGIN);
                }
            }
        }
        else if(v.getId() == R.id.btn_send_verify_code){
            String phone = mTelephone.getText().toString();

            if(isPhoneNumber(phone)){
                HashMap<String, String> param = new HashMap<String, String>();
                param.put("phone", phone);

                sendHttpRequest(
                        IHttpRequest.RequestMethod.POST_METHOD,
                        RemoteAPI.REQUEST_LOGIN_GET_VERIFY_CODE,
                        null,
                        param,
                        RemoteAPICmd.REQUEST_LOGIN_GET_VCODE);
            }
            else{
                ToastUtils.showLongToast(LogInActivity.this, "请填写正确的手机号码！");
            }
        }
        else{
            /**/
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            intent.putExtra("isLogIn", 0);
            setResult(MineFragment.ACTION_LOGIN, intent);
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobiles) {
		/*
		移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
		联通：130、131、132、152、155、156、185、186
		电信：133、153、180、189、（1349卫通）/^0?1[3|4|5|7|8][0-9]\d{8}$/
		总结起来就是第一位必定为1，第二位必定为3或5或8或7（电信运营商），其他位置的可以为0-9
		*/
        String telRegex = "[1][34578]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (mobiles == null || mobiles.equals(""))
            return false;
        else
            return mobiles.matches(telRegex);
    }

    /**
     * 判断手机号是否符合规范
     * @param phoneNo 输入的手机号
     * @return
     */
    public static boolean isPhoneNumber(String phoneNo) {
        if (phoneNo == null || phoneNo.equals("")){
            return false;
        }
        if (phoneNo.length() == 11) {
            for (int i = 0; i < 11; i++) {
                if (!PhoneNumberUtils.isISODigit(phoneNo.charAt(i))) {
                    return false;
                }
            }
            Pattern p = Pattern.compile("^((13[^4,\\D])" + "|(134[^9,\\D])" +
                    "|(14[5,7])" +
                    "|(15[^4,\\D])" +
                    "|(17[3,6-8])" +
                    "|(18[0-9]))\\d{8}$");
            Matcher m = p.matcher(phoneNo);
            return m.matches();
        }
        return false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onHttpResponse(int actionId, String response) {
        try {
            JSONObject res = new JSONObject(response);
            Gson gson = new Gson();
            Log.d(TAG, "onResponse: " + response);

            if(actionId == RemoteAPICmd.REQUEST_LOGIN_GET_VCODE){
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    mIsTimeout = false;
                    ToastUtils.showLongToast(LogInActivity.this, "验证码已发送！");

                    Message count = new Message();
                    count.what = MSG_TIMEOUT_COUNT;
                    count.obj = 60;
                    mHandler.sendMessage(count);
                }
                else{
                    ToastUtils.showLongToast(LogInActivity.this, "验证码发送失败！");
                }
            }
            else if(actionId == RemoteAPICmd.REQUEST_LOGIN){
                dismissLoadingDialog();
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    JSONObject data = res.getJSONObject("data");
                    LogInInfo loginInfo = gson.fromJson(data.toString(), LogInInfo.class);
                    AuthController.Instance().setToken(loginInfo.getToken());
                    ToastUtils.showLongToast(LogInActivity.this, "登录成功！");
                    Intent intent = new Intent();
                    intent.putExtra("isLogIn", 1);
                    setResult(MineFragment.ACTION_LOGIN, intent);
                    UserInfoController.Instance().updateUserInfo();
                    EnterPlatformInfoController.Instance().updateEnterStatus();
                    finish();
                }
                else{
                    ToastUtils.showLongToast(LogInActivity.this, "登录失败！");
                }
            }
            else{

            }
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onHttpErrorResponse(int actionId, String response) {
        if(actionId == RemoteAPICmd.REQUEST_LOGIN){
            dismissLoadingDialog();
        }
        else{

        }
    }
}